#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2023/12/15 17:51
# @Author  : FuKai ZHANG
# @File    : start_run_all_case.py
# @Description :所有用例的运行入口
import os
from utils.logging_tools.log_control import INFO,ERROR
from config.global_config import config
from utils.testcase_loader.loader_case import load_all_case_data_to_cache
from utils.other_tools.allure_server import start_allure_server
from utils.notification_tools.send_dingtalk import send_dingtalk_message



def run():
    # 从配置文件中获取项目名称
    INFO.info("开始初始化框架")
    # 手动触发用例初始化
    load_all_case_data_to_cache()

    pytest_args = [
        'pytest',  # 必须包含 pytest 命令
        '-s',
        '-v',
        '--alluredir', './report/tmp',
        '--clean-alluredir'
    ]


    if config.Pytest_xdis:
        INFO.info("启用 pytest-xdist 多进程执行模式")
        pytest_args.extend(['-n', 'auto', '--dist=loadfile'])  # 启用多进程
    else:
        INFO.info("启用 pytest 默认串行执行模式")

    try:
        command = ' '.join(pytest_args)
        os.system(command)
    except Exception as e:
        ERROR.error(f"执行pytest命令时发生异常: {e}")



    #生成 allure 报告
    try:
        os.system(r"allure generate ./report/tmp")
    except Exception as e:
        INFO.error(f"生成Allure报告时发生异常: {e}")

    #后台启动allure服务并发送消息通知
    try:
        url = start_allure_server()
        if url:
            INFO.info(f"Allure报告可访问地址: {url}")
            # 发送钉钉消息
            send_dingtalk_message(url)
        else:
            ERROR.error("无法启动 Allure 服务")

    except Exception as e:
        ERROR.error(f"发生异常: {e}")



if __name__ == '__main__':
    run()